package com.hrm.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.hrm.dao.ExtendsMapper;
import com.hrm.dao.UserMapper;
import com.hrm.dao.UserRoleMapper;
import com.hrm.entity.Menu;
import com.hrm.entity.OperList;
import com.hrm.entity.Role;
import com.hrm.entity.User;
import com.hrm.entity.UserRole;
import com.hrm.service.UserService;
import com.hrm.util.Config;
import com.hrm.util.Page;

public class UserServiceImpl implements UserService {
	private static final Log log = LogFactory.getLog(UserServiceImpl.class); 
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ExtendsMapper extendsMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	public UserRoleMapper getUserRoleMapper() {
		return userRoleMapper;
	}

	public void setUserRoleMapper(UserRoleMapper userRoleMapper) {
		this.userRoleMapper = userRoleMapper;
	}

	public ExtendsMapper getExtendsMapper() {
		return extendsMapper;
	}

	public void setExtendsMapper(ExtendsMapper extendsMapper) {
		this.extendsMapper = extendsMapper;
	}

	public UserMapper getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	public User login(String username, String password) {
		log.info("****** Do method login(String username, String password) begin,params info ==== [ username="+username+",password="+password+" ]");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", username);
		map.put("password", password);
		List<User> list=userMapper.selectUserByMap(map);
		if(list==null||list.size()<=0){
			log.error("****** Do method login(String username, String password) end,return info ==== [ User=null ]");
			return null;
		}else{
			log.info("****** Do method login(String username, String password) end,return info ==== [ User="+list.get(0)+" ]");
			return list.get(0);
		}
	}

	public List<OperList> getPermission(long userId) {
		log.info("****** Do method getPermission(long userId) begin,params info ==== [ userId="+userId+" ]");
		List<OperList> operLists = new ArrayList<OperList>();
		List<Menu> menus=extendsMapper.getMenusByUserId(userId);
		for (Menu menu : menus) {
			OperList operList = new OperList();
			operList.setMenu(menu);
			operList.setActions(extendsMapper.getActionsByUserIdAndMenuId(userId, menu.getId()));
			operLists.add(operList);
		}
		log.info("****** Do method getPermission(long userId) end,return info ==== [ List<OperList>="+operLists+" ]");
		return operLists;
	}

	public List<User> getUsers(Page page) {
		log.info("****** Do method getUsers(Page page) begin,params info ==== [page="+page+"]");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("currentStart", page.getCurrentStart()-1);
		map.put("currentEnd", page.getCurrentStart()+page.getPagesize()-1);
		List<User> users = userMapper.selectUserByMap(map);
		log.info("****** Do method getUsers(Page page) end,return info ==== [ List<User>="+users+" ]");
		return users;
	}
	public List<User> getUsers(Page page,String orderByStr) {
		log.info("****** Do method getUsers(Page page,String orderByStr) begin,params info ==== [ page="+page+",orderByStr="+orderByStr+" ]");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("currentStart", page.getCurrentStart()-1);
		map.put("currentEnd", page.getCurrentStart()+page.getPagesize()-1);
		map.put("orderBy", orderByStr);
		List<User> users = userMapper.selectUserByMap(map);
		log.info("****** Do method getUsers(Page page,String orderByStr) end,return info ==== [ List<User>="+users+" ]");
		return users;
	}

	public int getUserCounts() {
		log.info("****** Do method getUserCounts() begin,no params info");
		int cnts=-1;
		cnts=userMapper.getAllUserCounts();
		log.info("****** Do method getUserCounts() end,return info ==== [ int="+cnts+" ]");
		return cnts;
	}

	public List<Role> getRolesByUserId(long userId) {
		log.info("****** Do method getRolesByUserId(long userId) begin,params info ==== [ userId="+userId+" ]");
		List<Role> roles = extendsMapper.getRolesByUserId(userId);
		log.info("****** Do method getRolesByUserId(long userId) end,return info ==== [ List<Role>="+roles+" ]");
		return roles;
	}
	@Transactional
	public int addUser(User user, String[] roleids) {
		log.info("****** Do method addUser(User user, String[] roleids) begin,params info ==== [ user="+user+",roleids="+roleids+" ]");
		int cnts=-1;
		cnts=userMapper.insertUser(user);
		for (String s : roleids) {
			UserRole userRole = new UserRole();
			userRole.setRoleId(Integer.parseInt(s));
			userRole.setUserId(user.getId());
			userRole.setCreateDate(new Date());
			userRole.setCreateUserId(user.getCreateUserId());
			userRole.setCreateUserName(user.getCreateUserName());
			userRoleMapper.insertUserRole(userRole);
			log.info("insert one record into user_role, param ="+userRole);
		}
		log.info("****** Do method addUser(User user, String[] roleids) end,return info ==== [ int="+cnts+" ]");
		return cnts;
	}

	public User getUserById(long id) {
		log.info("****** Do method getUserById(long id) begin,params info ==== [ id="+id+" ]");
		User user =userMapper.selectUserById(id);
		log.info("****** Do method getUserById(long id) end,return info ==== [ User="+user+" ]");
		return user;
	}
	@Transactional
	public int updateUser(User user, String[] roleids) {
		log.info("****** Do method updateUser(User user, String[] roleids) begin,params info ==== [ user="+user+",roleids="+roleids+" ]");
		int cnts=-1;
		cnts=userMapper.updateUser(user);
		Map<String, Object> tMap = new HashMap<String, Object>();
		tMap.put("userId", user.getId());
		userRoleMapper.deleteUserRoleByMap(tMap);
		log.info("delete all user_role records where userId="+user.getId());
		for (String s : roleids) {
			UserRole userRole = new UserRole();
			userRole.setRoleId(Integer.parseInt(s));
			userRole.setUserId(user.getId());
			userRole.setCreateDate(new Date());
			userRole.setCreateUserId(user.getCreateUserId());
			userRole.setCreateUserName(user.getCreateUserName());
			userRoleMapper.insertUserRole(userRole);
			log.info("insert one record into user_role, param ="+userRole);
		}
		log.info("****** Do method updateUser(User user, String[] roleids) end,return info ==== [ int="+cnts+" ]");
		return cnts;
	}

	@Transactional
	public int deleteUserById(String userids) {
		log.info("****** Do method deleteUserById(String userids) begin,params info ==== [ userids="+userids+" ]");
		Map<String,Object> map = new HashMap<String,Object>();
		String[] tmp=userids.split(",");
		Integer[] ids = new Integer[tmp.length];
		for(int i=0;i<tmp.length;i++){
			ids[i]=Integer.parseInt(tmp[i]);
		}
		List<Integer> users=Arrays.asList(ids);
		map.put("userids", users);
		userMapper.deleteUserByMap(map);//先删除用户
		log.info("delete all user records where user's id in ("+userids+"}");
		int cnts=-1;
		cnts=userRoleMapper.deleteUserRoleByMap(map);//然后删除用户与角色的映射关系表
		log.info("delete all user_role records where user's id in ("+userids+"}");
		log.info("****** Do method deleteUserById(String userids) end,return info ==== [ int="+cnts+" ]");
		return cnts;
	}

	public int resetPwdToDefault(String userids) {
		log.info("****** Do method resetPwdToDefault(String userids) begin,params info ==== [ userids="+userids+" ]");
		Map<String,Object> map = new HashMap<String,Object>();
		String[] tmp=userids.split(",");
		Integer[] ids = new Integer[tmp.length];
		for(int i=0;i<tmp.length;i++){
			ids[i]=Integer.parseInt(tmp[i]);
		}
		List<Integer> users=Arrays.asList(ids);
		map.put("userids", users);
		map.put("newPassword", Config.DEFAULT_PWD);
		log.info("default password is "+Config.DEFAULT_PWD);
		int cnts=-1;
		cnts = userMapper.updateUserByMap(map);
		log.info("****** Do method resetPwdToDefault(String userids) end,return info ==== [ int="+cnts+" ]");
		return cnts;
	}

	public List<User> getUsersByName(String username,Page page) {
		log.info("****** Do method getUsersByName(String username,Page page) begin,params info ==== [ username="+username+",page="+page+" ]");
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("likeUserName", username);
		map.put("currentStart", page.getCurrentStart()-1);
		map.put("currentEnd", page.getCurrentStart()+page.getPagesize()-1);
		List<User> users= userMapper.selectUserByMap(map);
		log.info("****** Do method getUsersByName(String username,Page page) end,return info ==== [ List<User>="+users+" ]");
		return users;
	}

	public int getUserByNameCounts(String username) {
		log.info("****** Do method getUserByNameCounts(String username) begin,params info ==== [ username="+username+" ]");
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("likeUserName", username);
		int cnts=-1;
		cnts = userMapper.getUserCountsByMap(map);
		log.info("****** Do method getUserByNameCounts(String username) end,return info ==== [ int="+cnts+" ]");
		return cnts;
	}

}
